class OrdersController < ApplicationController
  include ControllerHelper
  before_filter :init, :only => [:new, :create, :edit, :index, :show]
  before_filter :require_user, :only => [:new, :create]
  before_filter :require_operator, :only => [:operator, :edit]
  def new
    if find_cart.get_items.nil? || find_cart.get_items.size == 0
      redirect_to cart_show_path and return
    end
    @page["styles"] << "roundmenuUI"
    @page["meta"] = false
    @page["name"] = "order"
    @page["not_show"] = "create"
    @order = Order.new
    @order.address = current_user.address
    @order.phone = current_user.phone
  end

  def create
    @order = Order.new(:address => params[:order][:address], :phone => params[:order][:phone])
    @order.user_id = current_user.id
    @order.operator_id = 0
    @order.status = "new"
    cart = find_cart
    redirect_to root_path and return if cart.empty?
    cart.get_items.each do |key, value|
      @order.items << Item.new(:product_id => key, :quantity => value)
    end
    @page["meta"] = false
    #    if verify_recaptcha && @order.save TODO: uncomment
    if @order.save
      @page["name"] = "order.thanks"
      cart.clear
      Notifier.for_operator(edit_order_url(:id => @order.id), @order, @site["site"]["email"]).deliver
      @total = cart.get_total
    else
      @page["styles"] << "roundmenuUI"
      @page["name"] = "order"
      @page["not_show"] = "create"
      render :action => "new"
    end
  end
  
  def show_admin
    @page["styles"] << ["roundmenuAdmin", "roundmenuUI"]
    @page["meta"] = false
    @order = Order.find(:first, :conditions => ["id = ?", params[:id]])
    @items = {}
    @order.items.each do |item|
      @items[item.product_id] = item.quantity
    end
    @user = @order.user
    get_ordered_shops
    render :layout => "cms"
  end

  def operator
    conditions = ""
    begin
      @filter = Order.new params[:filter]
    rescue
      @filter = Order.new
    end      
    per_page = params[:per_page] ||= @site["per_page"]["operator"]["orders"]
    conditions = merge_conditions(conditions, ["created_at between ? and ?", @filter.start_date, @filter.end_date]) if @filter.start_date && @filter.end_date
    conditions = merge_conditions(conditions, ["status = ?", @filter.status]) if @filter.status && !@filter.status.empty?
    conditions = merge_conditions(conditions, ["operator_id = ?", @filter.operator_id]) if @filter.operator_id && @filter.operator_id > 0
    @orders = Order.find(:all, :conditions => conditions).paginate(:page => params[:page], :per_page => per_page)
    @excel_link = params[:filter].to_param
    #raise @excel_link.inspect
    set_operator_settings
    render :layout => "cms"
  end

  def excel
    conditions = ""
    begin
      @filter = Order.new params[:filter]
    rescue
      @filter = Order.new
    end      
    conditions = merge_conditions(conditions, ["created_at between ? and ?", @filter.start_date, @filter.end_date]) if @filter.start_date && @filter.end_date
    conditions = merge_conditions(conditions, ["status = ?", @filter.status]) if @filter.status && !@filter.status.empty?
    conditions = merge_conditions(conditions, ["operator_id = ?", @filter.operator_id]) if @filter.operator_id && @filter.operator_id > 0
    orders = Order.find(:all, :conditions => conditions)
    send_data create_excel(orders), :filename => 'orders.xls', :type => 'application/xls'
  end

  def create_excel orders
    report = StringIO.new
    workbook = Spreadsheet::Excel.new(report)
    worksheet = workbook.add_worksheet("Orders")
    excel_headers = YAML::load(File.open("#{Rails.root}/config/locales/#{I18n.locale}.yml"))["en"]["orders"]["excel"]["headers"]
    excel_styles = {}
    excel_styles[:header] = Spreadsheet::Format.new :color => :silver, :pattern => 1, :pattern_fg_color => :black, :weight => :bold, :size => 10
    excel_styles[0] = Spreadsheet::Format.new :color => :black, :pattern => 1, :pattern_fg_color => :gray, :size => 9
    excel_styles[1] = Spreadsheet::Format.new :color => :black, :pattern => 1, :pattern_fg_color => :silver, :size => 9
    worksheet.row(0).default_format = excel_styles[:header]
    excel_headers.each do |key, value|
      worksheet.row(0).push value
    end
    row = 1
    orders.each_with_index do |order, order_index|
      @items = {}
      order.items.each do |item|
        @items[item.product_id] = item.quantity
      end
      get_ordered_shops
      order_sum = 0
      order_delivery = 0
      @order_shops.each do |shop|
        shop_sum = 0
        shop.get_order_categors.each do |categor|
          categor.get_order_products.each do |product|
            worksheet.row(row).default_format = excel_styles[order_index % 2]
            worksheet.write(row, 1, shop.town.name)
            worksheet.write(row, 2, shop.name)
            worksheet.write(row, 3, categor.name)
            worksheet.write(row, 4, product.name)
            worksheet.write(row, 5, get_hrn(product.price))
            worksheet.write(row, 6, @items[product.id])
            shop_sum += product.price * @items[product.id]
            worksheet.write(row, 7, get_hrn(product.price * @items[product.id]))
            row += 1
          end
        end
        order_sum += shop_sum
        order_delivery += shop.delivery
        worksheet.row(row).default_format = excel_styles[order_index % 2]
        worksheet.write(row, 1, shop.town.name)
        worksheet.write(row, 2, shop.name)
        worksheet.write(row, 7, get_hrn(shop_sum))
        worksheet.write(row, 8, get_hrn(shop.delivery))
        row += 1
      end
      worksheet.row(row).default_format = excel_styles[order_index % 2]
      worksheet.write(row, 0, order.id)
      worksheet.write(row, 7, get_hrn(order_sum))
      worksheet.write(row, 8, get_hrn(order_delivery))
      worksheet.write(row, 9, get_hrn(order.extra_price))
      worksheet.write(row, 10, order.extra_comment)
      total = order_sum + order_delivery
      total += order.extra_price if order.extra_price
      worksheet.write(row, 11, get_hrn(total))
      user = order.user
      worksheet.write(row, 12, "#{user.firstname} #{user.lastname}")
      if order.operator_id > 0
        operator = User.find(:first, :conditions => ["id = ?", order.operator_id])
        worksheet.write(row, 13, "#{operator.firstname} #{operator.lastname}")
      end
      worksheet.write(row, 14, I18n.t("site.cms.operator.order.status.#{order.status}"))
      worksheet.write(row, 15, I18n.l(order.created_at, :format => :long))
      row += 1
    end
    worksheet.column(0).width = 4
    worksheet.column(1).width = 10
    worksheet.column(2).width = 20  
    worksheet.column(3).width = 10
    worksheet.column(4).width = 20
    worksheet.column(5).width = 10
    worksheet.column(6).width = 10
    worksheet.column(7).width = 10
    worksheet.column(8).width = 12
    worksheet.column(9).width = 15
    worksheet.column(10).width = 15
    worksheet.column(11).width = 15
    worksheet.column(12).width = 17
    worksheet.column(13).width = 12
    worksheet.column(14).width = 12
    worksheet.column(15).width = 25
    
    workbook.close
    report.string
  end
  
  def edit
    @page["styles"] << ["roundmenuAdmin", "roundmenuUI"]
    @page["meta"] = false
    @order = Order.find(:first, :conditions => ["id = ?", params[:id]])
    @user = @order.user
    cart = find_cart
    unless cart.order_id && cart.order_id == @order.id
      cart.clear
      hash = {}
      @order.items.each do |item|
        hash[item.product_id] = item.quantity
      end
      cart.add_items(hash)
      cart.order_id = @order.id
    end
    @items = find_cart.get_items
    get_ordered_shops
    @for_operator = true
    @for_edit = true
    @for_edit = false if @order.status == "approved"
    render :layout => "operator"
  end

  def update
    find_cart.update_items(params[:items])
    @order = Order.find(:first, :conditions => ["status IN ('new') and operator_id IN (0,?) and id=?", current_user.id, params[:id]])
    @order.update_attributes(params[:order])
    redirect_to edit_order_path(params[:id])
  end

  def submit
    @order = Order.find(:first, :conditions => ["status IN ('new') and operator_id IN (0,?) and id=?", current_user.id, params[:id]])
    @order.operator_id = current_user.id
    @order.status = "approved"
    cart = find_cart
    cart.get_items.each do |key, value|
      create_new = true
      @order.items.each do |item|
        if key == item.product_id
          item.quantity = value
          item.save
          create_new = false
        end
      end
      @order.items << Item.new(:product_id => key, :quantity => value) if create_new
    end
    @order.items.delete_if do |item|
      !cart.get_items.key?(item)
    end
    @items = find_cart.get_items
    get_ordered_shops
    total_price = 0
    @order_shops.each do |shop|
      shop.get_order_categors.each do |order_categor|
        order_categor.get_order_products.each do |order_product|
          total_price += order_product.price * @items[order_product.id]
        end
      end
      total_price += shop.delivery
    end
    total_price += @order.extra_price if @order.extra_price
    @order.total_price = total_price
    if @order.save
      Notifier.for_user(@order, order_url(:id => @order.id), root_url, @site["site"]["email"]).deliver
      cart.clear
      redirect_to order_operator_path and return
    else
      render :action => :edit, :layout => "operator"
    end
  end

  def index
    @page["name"] = "order"
    @page["meta"] = false
    per_page = params[:per_page] ||= @site["per_page"]["user"]["orders"]
    @orders = Order.find(:all, :conditions => ["status IN ('approved') and user_id = ?", current_user.id]).uniq.paginate(:page => params[:page], :per_page => per_page)
  end

  def show
    @page["meta"] = false
    @order = Order.find(:first, :conditions => ["status IN ('approved') and user_id = ? and id = ?", current_user.id, params[:id]])
    @items = {}
    @order.items.each do |item|
      @items[item.product_id] = item.quantity
    end
    @for_operator = false
    @for_edit = false
    get_ordered_shops
  end

  def pay
    @order = Order.find(:first, :conditions => ["status IN ('approved') and user_id = ? and id = ?", current_user.id, params[:id]])
    raise "TODO: Implement pay #{@order.inspect}"
  end

end
